package com.demo.juc;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
import java.util.concurrent.TimeUnit;

import org.junit.Before;
import org.junit.Test;

public class ThreadPoolExecutorTest {

	private static ThreadPoolExecutor executor = null;
	
	private static final int DEFAULT_SIZE = Integer.SIZE - 22;
	
	//RejectedExecutionHandler(拒绝策略)
	//CallerRunsPolicy 在调用者线程执行当前任务，不抛异常
	//DiscardPolicy: 抛弃策略，直接丢弃任务，不抛异常
	//DiscardOldersPolicy: 抛弃最老的任务，执行当前任务，不抛异常
	@Before
	public void before(){
		executor = new ThreadPoolExecutor(DEFAULT_SIZE, DEFAULT_SIZE + 10, 1000, TimeUnit.MILLISECONDS,  new LinkedBlockingQueue<Runnable>(), new AbortPolicy());
	}
	
	@Test
	public void test(){
		executor.submit(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("匿名内部类。。。");
			}
		});
	}
	
	@Test
	public void test2(){
//		System.out.println(DEFAULT_SIZE);
		for (int i = 0; i < DEFAULT_SIZE; i++) {
			executor.submit((new Runnable() {
				@Override
				public void run() {
					System.out.println("线程号:" + Thread.currentThread().getId());
					try {
						Thread.sleep(10000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}));
		}
		
	}
	
	@SuppressWarnings("rawtypes")
	@Test
	public void test3(){
		MyThreadPoolExecutor executor = new MyThreadPoolExecutor(DEFAULT_SIZE, DEFAULT_SIZE, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
		
		for (int i = 0; i < DEFAULT_SIZE/2; i++) {
			executor.submit(new Callable<String>() {
				@Override
				public String call() throws Exception {
					System.out.println("当前线程:" + Thread.currentThread().getId() + "这个是实现的calleble接口");
					Thread.sleep(5000);
					return "hahha";
				}
			});
		}
		
	}
	
	@Test
	public void test4(){
		MyThreadPoolExecutor executor = new MyThreadPoolExecutor(DEFAULT_SIZE, DEFAULT_SIZE, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
		
		List<Callable<String>> list = new ArrayList<>();
		for (int i = 0; i < DEFAULT_SIZE/2; i++) {
			list.add(new Callable<String>() {
				@Override
				public String call() throws Exception {
					System.out.println("当前线程:" + Thread.currentThread().getId() + "这个是实现的calleble接口");
					Thread.sleep(5000);
					return "hahha";
				}
			});
		}
		
		try {
			executor.invokeAll(list);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
}
